<template>
  <div class="flex flex-col h-full">
    <a-card :body-style="{ padding: '8px 12px' }">
      <a-form ref="formRef" :model="formState" class="flex justify-between">
        <div class="flex">
          <a-form-item name="brName" class="w-[260px] mr-3 !mb-0">
            <SelectTable
              v-model:value="formState.brName"
              :search-params="{ stdate: formState.stdate, eddate: formState.eddate, type: '2' }"
              type="门诊挂号患者列表"
              placeholder="姓名/助记码/卡号/手机号/身份证号"
              @select="onSelect"
            />
          </a-form-item>
          <a-form-item label="挂号时间" class="!mb-0">
            <div class="flex">
              <a-date-picker v-model:value="formState.stdate" placeholder="开始时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
              <a-date-picker v-model:value="formState.eddate" class="ml-2" placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </div>
          </a-form-item>
        </div>
        <div>
          <a-button style="margin: 0 8px" @click="onClickReset">重置</a-button>
          <a-button type="primary" @click="onClickRefresh">刷新</a-button>
        </div>
      </a-form>
    </a-card>

    <PatientInfoHeader :patient-info="patientInfo" class="mt-2">
      <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
      <div>
        <div class="flex items-center">
          <LabelValue label="卡号" :value="patientInfo.brId" :width="160" label-class="w-[52px] text-right" />
          <LabelValue label="病案号" :value="patientInfo[isBGMSG ? 'brBlkh' : 'oprSn']" :width="160" />
          <LabelValue label="科室" :value="patientInfo.ksmc" :width="160" />
          <LabelValue label="挂号类别" :value="patientInfo.ghlb" :width="160" />
        </div>
        <div class="flex items-center">
          <LabelValue label="门诊号" :value="patientInfo.jzbh" :width="160" />
          <LabelValue label="病历号" :value="patientInfo[isBGMSG ? 'oprSn' : 'brBlkh']" :width="160" />
          <LabelValue label="医生" :value="patientInfo.empName" :width="160" />
          <LabelValue label="挂号时间" :value="patientInfo.ghsj" :width="200" />
        </div>
      </div>
    </PatientInfoHeader>
    <div class="mt-2 flex flex-1 overflow-hidden">
      <div class="w-1/4">
        <a-card>
          <BaseTitle title="收费类别" class="!mb-2.5" />
          <BaseTable :loading="loading" column-code="00001107" fill :data-source="tableDataType" bordered>
            <template #bodyCell="{ column, index }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
            </template>
            <template #summary>
              <a-table-summary-row v-if="tableDataType.length > 0">
                <a-table-summary-cell>
                  <a-typography-text>合计</a-typography-text>
                </a-table-summary-cell>
                <a-table-summary-cell />
                <a-table-summary-cell />
                <a-table-summary-cell />
                <a-table-summary-cell class="text-right">
                  <a-typography-text>{{ formatAmount(medicalPrice) }}</a-typography-text>
                </a-table-summary-cell>
              </a-table-summary-row>
            </template>
          </BaseTable>
        </a-card>
      </div>
      <div ref="leftRef" class="w-3/4 ml-2 relative">
        <a-card :style="{ height: tableCardHeight + 'px' }">
          <div class="flex justify-between items-center">
            <div class="flex items-center">
              <BaseTitle title="收费明细" class="!mb-2.5">
                <div class="ml-4 flex items-center">
                  <span class="font-normal pr-2">处置</span>
                  <a-switch v-model:checked="czFlag" :disabled="!jzbh" @change="onClickRefresh()" />
                  <span class="font-normal pr-2 ml-2">处方</span>
                  <a-switch v-model:checked="cfFlag" :disabled="!jzbh" @change="onChangeCfSwitch" />
                  <a-select
                    v-if="cfFlag"
                    v-model:value="cfbhList"
                    :max-tag-count="3"
                    :disabled="!jzbh"
                    mode="multiple"
                    placeholder="请选择"
                    :options="cfbhData"
                    allow-clear
                    class="ml-2 w-[260px]"
                    @change="onClickRefresh()"
                  />
                </div>
              </BaseTitle>
            </div>
            <div class="flex">
              <div class="ml-4 flex items-center">
                <span class="font-normal pr-2">显示套餐</span>
                <a-switch v-model:checked="packageSwitch" :disabled="!tableDataDetail.length" @change="onClickRefresh()" />
              </div>
            </div>
          </div>

          <BaseTable
            :loading="loading"
            column-code="00001108"
            :data-source="tableDataDetail"
            :height="tableHeight"
            row-key="id"
            bordered
            :row-selection="{ selectedRowKeys: tableDetailId, onChange: onSelectChange }"
          >
            <template #bodyCell="{ column, index, record, text }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
              <template v-if="column.dataIndex === 'xmmc'">
                <MedicineInfo :value="{ mc: record?.xmmc, gg: record?.gg, cj: record?.cj }" />
              </template>
              <template v-if="column.dataIndex === 'sl'">
                {{ formatAmount(text) }}
              </template>
              <template v-if="column.dataIndex === 'je'">
                {{ formatAmount(text) }}
              </template>
              <template v-if="column.dataIndex === 'yzzt'">
                <a-tag v-if="!+record.yzzt" color="green">正常</a-tag>
                <a-tag v-else color="red">失效</a-tag>
              </template>
            </template>
          </BaseTable>
          <div class="text-right w-full absolute bottom-0 left-0 p-4">
            医疗费：<span class="text-xl font-bold text-red-500">￥{{ formatAmount(medicalPrice) }}</span>
          </div>
        </a-card>
        <div ref="bottomRef" class="absolute w-full bottom-1">
          <div v-if="showPrescription" class="max-h-80 overflow-auto overflow-x-hidden">
            <a-card v-for="(item, index) in prescriptionList" :key="index" class="mt-2 pb-3">
              <BaseTitle :title="'中药处方' + (index + 1) + '-加工'" />
              <div class="flex justify-between">
                <div class="flex">
                  <div class="flex flex-col mr-5">
                    <a-select ref="select" v-model:value="item.drugStoreId" style="width: 220px" placeholder="请选择" :options="drugRoomList" />
                    <a-radio-group v-model:value="item.jzfs" class="mt-5" @change="onChangeRadio(item)">
                      <a-radio value="自煎">自煎</a-radio>
                      <a-radio value="代煎">代煎</a-radio>
                    </a-radio-group>
                  </div>
                  <a-divider type="vertical" :style="{ height: '80px', margin: '0 16px' }" />
                  <div>
                    <div class="flex mb-5">
                      <div class="font-bold mx-2 mt-1 w-7">加工</div>
                      <div
                        :class="[
                          'order-footer',
                          'w-[450px]',
                          item.jzfs === '自煎' ? '!cursor-not-allowed bg-slate-100' : '',
                          item.processMethod.processMethodName ? '' : 'color-placeholder'
                        ]"
                        @click="onClickProcessOpen(item, 1)"
                      >
                        {{ generateProcess(item, item?.processMethod) }}
                      </div>
                    </div>
                    <div class="flex">
                      <div class="font-bold mx-2 mt-1 w-7">快递</div>
                      <div :class="['order-footer', 'w-[450px]', item.express.sjr ? '' : 'color-placeholder']" @click="onClickProcessOpen(item, 2)">
                        {{ generateExpress(item.express) }}
                      </div>
                      <a-button type="text" danger size="small" @click="onclickDelete(item)">删除</a-button>
                    </div>
                  </div>
                </div>
                <div>
                  <div class="mb-6 truncate w-48 text-right">
                    加工费：<span class="text-xl font-bold text-red-500"
                      >￥{{ item.processMethod?.processMethodCost ? formatAmount(item.processMethod?.processMethodCost) : '0.00' }}</span
                    >
                  </div>
                  <div class="truncate w-48 text-right">
                    快递费：<span class="text-xl font-bold text-red-500"
                      >￥{{ item.express?.expressCost ? formatAmount(item.express?.expressCost) : '0.00' }}</span
                    >
                  </div>
                </div>
              </div>
            </a-card>
          </div>

          <!-- <a-card class="my-2">
            <div class="flex items-center justify-between">
              <div class="flex flex-1 items-center">
                <BaseTitle class="!w-16 !pr-0" title="优惠" />
                <a-input
                  v-model:value="discountAmount"
                  v-input:float.2
                  v-input-selection
                  class="w-1/6 mr-4 discount-input"
                  placeholder="0.00"
                  @blur="getReceiptsAmount"
                >
                  <template #prefix> <span class="text-gray-400">￥</span> </template>
                </a-input>
                <a-input v-model:value="discountReason" class="w-1/2" placeholder="请输入优惠原因" />
              </div>
              <div>
                优惠：<span class="text-xl font-bold text-red-500 truncate"
                  >￥{{ formatAmount(discountAmount || 0) ? formatAmount(discountAmount) : '0.00' }}</span
                >
              </div>
            </div>
          </a-card>
          <a-card class="mt-2">
            <div class="flex items-center justify-between">
              <BaseTitle class="!w-1/3" title="分币误差" />
              <div>
                分币：<span class="text-xl font-bold text-red-500 truncate">￥{{ formatAmount(differenceAmount) }}</span>
              </div>
            </div>
          </a-card> -->
          <!-- <a-card class="mt-2 w-full flex-1 border-t" :body-style="{ height: '100%', position: 'relative' }">
            <div class="text-right mr-2 mb-2 absolute bottom-0 right-0">
              <div class="my-2 font-bold text-lg">
                本次应收 <span class="text-xl text-red-500 font-bold">￥{{ formatAmount(medicalPrice) }}</span>
              </div>
              <a-button class="ml-2 w-28" size="large" @click="onClickReset">重置</a-button>
              <a-button type="primary" class="ml-2 w-28" size="large" :disabled="!formState.brName" @click="onSuccessPreferential"> 收费 </a-button>
            </div>
          </a-card> -->
          <a-card class="mt-2">
            <div class="flex justify-end items-center">
              <div class="mr-4">
                本次应收：<span class="text-xl font-bold text-red-500">￥{{ formatAmount(priceAway) }}</span>
              </div>
              <a-button class="ml-2 w-28" size="large" @click="onClickReset">重置</a-button>
              <a-button type="primary" class="ml-2 w-28" size="large" :disabled="!formState.brName" @click="onClickCharge"> 收费 </a-button>
            </div>
          </a-card>
        </div>
      </div>
    </div>
    <ChargeModal v-model:open="chargeOpen" :br-id="formState.brId" :business-data="{ ...formState, ysje: priceAway }" @success="onSuccessPrice" />
    <ModalExpress v-model:open="expressOpen" :row-data="orderData.express" :br-id="formState.brId" @ok="onProcessOk" />
    <ModalProcess v-model:open="processOpen" :row-data="orderData.processMethod" @ok="onProcessOk" />
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import BaseTitle from '@/components/BaseTitle'
import SelectTable from '@/components/SelectTable'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import ModalExpress from '@/components/ModalExpress'
import ModalProcess from '@/components/ModalProcess'
import ChargeModal from '@/components/ChargeModal'

const loading = ref(false)
const tableDataType = ref([])
const tableDataDetail = ref([])
const formState = ref({
  stdate: dayjs().format('YYYY-MM-DD'),
  eddate: dayjs().format('YYYY-MM-DD')
})
// const activeKey = ref('自费')
const chargeOpen = ref(false)
const patientInfo = ref([])
const jzbh = ref('')
// const categoryPrice = ref(0)
const tableDetailId = ref([])
const formRef = ref(null)
const drugRoomList = ref([])
const discountAmount = ref('0.00')
// const discountReason = ref('')
const showPrescription = ref(false)
const prescriptionList = ref([])
const processOpen = ref(false)
const expressOpen = ref(false)
const orderData = ref({})
const priceNum = ref(0)
const priceAway = ref(0)
const differenceAmount = ref(0)
const medicalPrice = ref(0)
const packageSwitch = ref(true)
const czFlag = ref(true)
const cfFlag = ref(true)
const cfbhData = ref([])
const cfbhList = ref([])

const onClickReset = () => {
  formRef.value.resetFields()
  jzbh.value = ''
  formState.value.stdate = dayjs().format('YYYY-MM-DD')
  formState.value.eddate = dayjs().format('YYYY-MM-DD')
  differenceAmount.value = 0
  discountAmount.value = '0.00'
  prescriptionList.value = []
  patientInfo.value = {}
  packageSwitch.value = true
  cfbhData.value = []
  cfbhList.value = []
  czFlag.value = true
  cfFlag.value = true
}
const onClickRefresh = async () => {
  await chargeDetailList()
  getFeeCategoryList()
  getAmount()
}
const onChangeCfSwitch = async (e) => {
  if (!e) {
    cfbhData.value = []
    cfbhList.value = []
  } else {
    await getCfData()
  }
  await chargeDetailList()
  getFeeCategoryList()
  getAmount()
}

const onSelect = async (select) => {
  formState.value.brName = select.brName
  // patientInfo.value = select
  jzbh.value = select.jzbh
  await getOutpInfo()
}

// 获取患者信息
const getOutpInfo = async () => {
  const { code, data, msg } = await post('/outp/mzys/getOutpRecordInfo', { mzjlbh: jzbh.value })
  if (code !== 0) return message.error(msg || '获取病历信息失败')
  patientInfo.value = data
}
const onSuccessPrice = async (params = {}) => {
  const { code, msg, data } = await post(
    params.zffs === '2' ? '/outp/oupCharge/doPaymentForScan' : '/outp/oupCharge/doSaveOutPFee',
    {
      ...params,
      sflb: 'MZ',
      ids: tableDetailId.value,
      jzbh: jzbh.value
    },
    {
      timeout: 2 * 60 * 1000 // 超时时间2分钟
    }
  )
  if (code !== 0) return message.error(msg)
  message.success(msg)
  chargeOpen.value = false
  onPrint(data)
  await onSaveMedicineList()
  await chargeDetailList()
  getFeeCategoryList()
  getAmount()
  onClickReset()
  // setTimeout(() => {
  //   window.open(`/api/v1/outp/outPrint/OutpatientChargeCertificate`)
  // }, 1500)
}
const onPrint = async (item = {}) => {
  if (getSystemConfig('PRINT_INVOICE_AFTER_CHARGE') === '0') return
  const { code, msg, data } = await post('/outp/oupCharge/PrintMedicareCharges', { jzbh: jzbh.value, pjhm: item.pjhm, sftfbs: '0' })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
const getFeeCategoryList = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getOutpClinicalOrderTypeList', { jzbh: jzbh.value, yzzt: 1, ids: tableDetailId.value })
  if (code !== 0) return message.error(msg)
  tableDataType.value = data
}

const chargeDetailList = async () => {
  const {
    code,
    data = [],
    msg
  } = await post('/outp/oupCharge/getOutpClinicalOrderInfoList', {
    jzbh: jzbh.value,
    // orderType: [0, 1],
    orderType: packageSwitch.value ? [0, 1] : [0, 2],
    yzzt: 1,
    jfzt: 0,
    czFlag: czFlag.value ? 1 : 0,
    cfFlag: cfFlag.value ? 1 : 0,
    cfbhList: cfbhList.value
  })
  if (code !== 0) return message.error(msg)
  tableDataDetail.value = data
  tableDetailId.value = data.map((item) => item.id)
  getReceiptsCount()
}
const onSelectChange = (selectedRowKeys) => {
  tableDetailId.value = selectedRowKeys
  getFeeCategoryList()
  getAmount()
}
const getAmount = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getOutpClinicalOrderInfoTotalCost', { jzbh: jzbh.value, ids: tableDetailId.value })
  if (code !== 0) return message.error(msg)
  medicalPrice.value = data
  getReceiptsAmount()
}

const onClickCharge = async () => {
  const { code, msg } = await post('/outp/oupCharge/doCheckClinicalOrdersIsSign', {
    ids: tableDetailId.value
  })
  if (code !== 0) return message.error(msg)
  chargeOpen.value = true
}
const getDrugRooms = async () => {
  const res = await post('/operation/opex/getDrugStoreInfoList', { status: 1 })
  if (res.code !== 0) return message.error(res.msg)
  drugRoomList.value = res.data.map((item) => {
    return { label: item.storeName, value: item.id }
  })
}

const getReceiptsCount = async () => {
  showPrescription.value = tableDataDetail.value.some((item) => item.lbmc === '中药费')
  await getPrescription()
  nextTick(() => {
    getOffsetHeight()
  })
}
const getPrescription = async () => {
  const { data, code, msg } = await post('/outp/outpClinicalOrder/getOutpTCMHeadList', { jzbh: [jzbh.value] })
  if (code !== 0) return message.error(msg)
  prescriptionList.value = data
  getReceiptsAmount()
}
const getCfData = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getOutpClinicalCfbhInfoList', {
    jzbh: jzbh.value,
    orderType: packageSwitch.value ? [0, 1] : [0, 2],
    yzzt: 1,
    jfzt: 0,
    jfztList: ['0', '3']
  })
  if (code !== 0) return message.error(msg)
  if (data && data.length > 0) {
    cfbhData.value = data.map((item) => {
      return { label: item.cfmc, value: item.cfbh }
    })
    cfbhList.value = data.map((item) => {
      return item.cfbh
    })
  } else {
    cfbhData.value = []
  }
}

const onChangeRadio = (row) => {
  orderData.value = row
  if (row.jzfs === '自煎') {
    row.processMethod = {}
  } else {
    row.processMethod = orderData.value.processMethod
  }
  getReceiptsAmount()
}

const generateProcess = (row, processMethod = {}) => {
  if (Object.keys(processMethod).length > 0) {
    return `${processMethod?.processMethodName} ${processMethod?.processMethodCmemo || ''}`
  }
  if (row.jzfs === '自煎' && Object.keys(processMethod).length === 0) {
    return '暂无加工'
  }
  if (row.jzfs === '代煎' && Object.keys(processMethod).length === 0) {
    return '点击填写'
  }
}
const generateExpress = (express = {}) => {
  if (Object.keys(express).length > 0) {
    return `${express.sjr}，${express.sjrtel}，${express.province}${express.city}${express.county}${express.patientAddressId} ${express.expressMode} ${
      express.expressCmemo || ''
    }`
  }
  if (Object.keys(express).length === 0) {
    return '点击填写'
  }
}
const onClickProcessOpen = (row, state) => {
  orderData.value = row
  if (row.jzfs === '代煎' && state === 1) {
    processOpen.value = true
  }
  if (state === 2) {
    expressOpen.value = true
  }
}
const onProcessOk = async (row) => {
  if (row.processMethodName) {
    orderData.value.processMethod = row
  } else {
    orderData.value.express = row
  }
  const findState = prescriptionList.value.findIndex((x) => x.drugStoreId === orderData.value.drugStoreId)
  if (findState !== -1) {
    prescriptionList.value.splice(findState, 1, orderData.value)
  }
  await onSaveMedicineList()
  getReceiptsAmount()
}
const onclickDelete = (row) => {
  row.express = {}
  getReceiptsAmount()
}
const onSaveMedicineList = () => {
  prescriptionList.value.forEach(async (item) => {
    const params = {
      keycode: jzbh.value,
      ...item
    }
    const { code, msg } = await post('/outp/outpClinicalOrder/doSaveOutpTCMHead', params)
    if (code !== 0) return message.error(msg || '操作失败')
  })
}

const getReceiptsAmount = async () => {
  priceNum.value = 0
  priceAway.value = 0
  prescriptionList.value.forEach((item) => {
    priceNum.value +=
      (item.processMethod.processMethodCost ? Number(item.processMethod.processMethodCost) : 0) +
      (item.express.expressCost ? Number(item.express.expressCost) : 0)
  })
  priceAway.value = Number(formatAmount(medicalPrice.value)) + priceNum.value
  // const { code, data } = await post('/outp/oupCharge/getPennyDiscount', {
  //   ysje: Number(priceAway.value), //应收金额
  //   yhje: Number(discountAmount.value) //优惠金额
  // })
  // if (code !== 0) return
  // differenceAmount.value = data.fbwc
  // categoryPrice.value = data.ssje
}
const getOffsetHeight = () => {
  tableCardHeight.value = leftRef.value?.offsetHeight - bottomRef.value?.offsetHeight - 6
  tableHeight.value = leftRef.value?.offsetHeight - bottomRef.value?.offsetHeight - 154
}

const bottomRef = ref()
const leftRef = ref()
const tableCardHeight = ref()
const tableHeight = ref()
onMounted(() => {
  nextTick(() => {
    getOffsetHeight()
  })
})
watch(jzbh, async () => {
  await getCfData()
  await chargeDetailList()
  getFeeCategoryList()
  getAmount()
  getDrugRooms()
})
</script>
<style lang="less" scoped>
.order-footer {
  @apply cursor-pointer border-b py-1;
}
:deep(.ant-tabs-content-holder) {
  overflow: hidden;
}
.discount-input {
  :deep(.ant-input) {
    text-align: right;
  }
}
.color-placeholder {
  color: var(--disabled-text-color);
}
</style>
